
const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Node)
    wrapper: cc.Node = null;

    childWposList: cc.Vec2[] = [];

    start () {
        this.childWposList = this.wrapper.children.map((node: cc.Node) => {
            return node.convertToWorldSpaceAR(cc.v2());
        });

        this.wrapper.on(cc.Node.EventType.TOUCH_START, this.onTap, this);
    }

    onTap (e: cc.Event.EventTouch) {
        let touchPos = e.getLocation();

        // 每个子节点与点击坐标的距离集合
        let dis_list: number[] = [];
        // 遍历所有子节点坐标得出与鼠标的距离然后升序排列
        let dis_list_sort = this.childWposList.map((wpos: cc.Vec2) => {
            console.log(touchPos, wpos);
            console.log(wpos.sub(touchPos), wpos.sub(touchPos).magSqr());
            let dis = wpos.sub(touchPos).magSqr();
            // 记录距离值
            dis_list.push(dis);
            return dis;
        });

        dis_list_sort.sort((a, b) => a-b);

        // 获取排序最前面的索引

        let nearest_index = dis_list.indexOf(dis_list_sort[0]);


        // 颜色修改
        // 先全部恢复白色
        this.wrapper.children.forEach((node: cc.Node) => {
            node.color = cc.Color.WHITE;
        });
        // 设置目标颜色 红色
        this.wrapper.children[nearest_index].color = cc.Color.RED;
    }
}
